package com.cap.bts.crmdp.dealer.card.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.cap.bts.framework.common.exception.AppException;

public class CSVUtils {

    private static final Logger LOGGER = Logger.getLogger(CSVUtils.class);

    private CSVUtils() {
    }
    
    public static File createCSVFile(List exportData, Map rowMapper, String outPutPath,
        String filename) throws AppException{

        File csvFile = null;
        BufferedWriter csvFileOutputStream = null;
        try {
            csvFile = new File(outPutPath + filename + ".csv");
            // csvFile.getParentFile().mkdir()
            File parent = csvFile.getParentFile();
            
            if (parent != null && !parent.exists() && parent.mkdirs()) {
                    LOGGER.info("parent.mkdirs success");
            }

            File f = new File(outPutPath + filename + ".csv");

            String absolutePath = f.getAbsolutePath();
            if(csvFile.createNewFile()){
                LOGGER.info("生成临时文件存放路径" + absolutePath);
                LOGGER.info("csvFile.createNewFile success");
            }
            OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(csvFile), "UTF-8");
            // osw.write(new String(new byte[] { (byte) 0xEF, (byte) 0xBB,(byte)
            // 0xBF }))
            osw.write(0xFEFF);
            // UTF-8使正确读取分隔符","
            csvFileOutputStream = new BufferedWriter(osw, 1024);
            // 写入文件头部
            for (Iterator propertyIterator = rowMapper.entrySet().iterator(); propertyIterator
                .hasNext();) {
                java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next();
                csvFileOutputStream.write("\"" + propertyEntry.getValue().toString() + "\"");
                if (propertyIterator.hasNext()) {
                    csvFileOutputStream.write(",");
                }
            }
            csvFileOutputStream.newLine();

            // 写入文件内容
            for (Iterator iterator = exportData.iterator(); iterator.hasNext();) {
                Object row = (Object) iterator.next();

                for (Iterator propertyIterator = rowMapper.entrySet().iterator(); propertyIterator
                    .hasNext();) {
                    java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator
                        .next();
                    csvFileOutputStream.write("\""
                        + BeanUtils.getProperty(row, propertyEntry.getKey().toString()) + "\"");
                    if (propertyIterator.hasNext()) {
                        csvFileOutputStream.write(",");
                    }
                }
                if (iterator.hasNext()) {
                    csvFileOutputStream.newLine();
                }
            }
            csvFileOutputStream.flush();
            if(csvFileOutputStream!=null){
                csvFileOutputStream.close();
            }
        }catch (IOException e) {
            throw new AppException("createCSVFile",e);
        }catch (IllegalAccessException e) {
            throw new AppException("createCSVFile",e);
        }catch (InvocationTargetException e) {
            throw new AppException("createCSVFile",e);
        }catch (NoSuchMethodException e) {
            throw new AppException("createCSVFile",e);
        }
        return csvFile;
    }
    
    public static File createCSVFile(List exportData, Map rowMapper, String outPutPath,
            String filename, String codeType) throws AppException{

            File csvFile = null;
            BufferedWriter csvFileOutputStream = null;
            try {
                csvFile = new File(outPutPath + filename + ".csv");
                // csvFile.getParentFile().mkdir()
                File parent = csvFile.getParentFile();
                
                if (parent != null && !parent.exists() && parent.mkdirs()) {
                        LOGGER.info("parent.mkdirs success");
                }

                File f = new File(outPutPath + filename + ".csv");

                String absolutePath = f.getAbsolutePath();
                if(csvFile.createNewFile()){
                    LOGGER.info("生成临时文件存放路径" + absolutePath);
                    LOGGER.info("csvFile.createNewFile success");
                }
                OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(csvFile), codeType);
                // osw.write(new String(new byte[] { (byte) 0xEF, (byte) 0xBB,(byte)
                // 0xBF }))
//                osw.write(0xFEFF);
                // UTF-8使正确读取分隔符","
                csvFileOutputStream = new BufferedWriter(osw, 1024);
                // 写入文件头部
                for (Iterator propertyIterator = rowMapper.entrySet().iterator(); propertyIterator
                    .hasNext();) {
                    java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next();
                    csvFileOutputStream.write(propertyEntry.getValue().toString());
                    if (propertyIterator.hasNext()) {
                        csvFileOutputStream.write(",");
                    }
                }
                csvFileOutputStream.newLine();

                // 写入文件内容
                for (Iterator iterator = exportData.iterator(); iterator.hasNext();) {
                    Object row = (Object) iterator.next();

                    for (Iterator propertyIterator = rowMapper.entrySet().iterator(); propertyIterator
                        .hasNext();) {
                        java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator
                            .next();
                        csvFileOutputStream.write(StringUtils.defaultString(BeanUtils.getProperty(row, propertyEntry.getKey().toString())));
                        if (propertyIterator.hasNext()) {
                            csvFileOutputStream.write(",");
                        }
                    }
                    if (iterator.hasNext()) {
                        csvFileOutputStream.newLine();
                    }
                }
                csvFileOutputStream.flush();
                if(csvFileOutputStream!=null){
                    csvFileOutputStream.close();
                }
            }catch (IOException e) {
                throw new AppException("createCSVFile",e);
            }catch (IllegalAccessException e) {
                throw new AppException("createCSVFile",e);
            }catch (InvocationTargetException e) {
                throw new AppException("createCSVFile",e);
            }catch (NoSuchMethodException e) {
                throw new AppException("createCSVFile",e);
            }
            return csvFile;
        }
}
